package cn.tb.pet.service.impl;

import cn.tb.basic.util.BaiduAuditUtils;
import cn.tb.basic.util.DistanceUtil;
import cn.tb.basic.util.Point;
import cn.tb.basic.util.SmsUtils;
import cn.tb.org.domain.Shop;
import cn.tb.org.mapper.ShopMapper;
import cn.tb.pet.domain.SearchMasterMsg;
import cn.tb.pet.domain.SearchMasterMsgAuditLog;
import cn.tb.pet.mapper.SearchMasterMsgAuditLogMapper;
import cn.tb.pet.mapper.SearchMasterMsgMapper;
import cn.tb.pet.service.ISearchMasterMsgService;
import cn.tb.basic.service.impl.BaseServiceImpl;
import cn.tb.user.domain.Logininfo;
import cn.tb.user.domain.User;
import cn.tb.user.mapper.UserMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author tangbo
 * @since 2022-06-28
 */
@Service
@Slf4j
public class SearchMasterMsgServiceImpl extends BaseServiceImpl<SearchMasterMsg> implements ISearchMasterMsgService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private SearchMasterMsgMapper searchMasterMsgMapper;
    @Autowired
    private SearchMasterMsgAuditLogMapper searchMasterMsgAuditLogMapper;
    @Autowired
    private ShopMapper shopMapper;

    /**
     * 发布寻主消息
     * @param msg
     * @param logininfo
     */
    @Override
    public void publish(SearchMasterMsg msg, Logininfo logininfo) {
        User user = userMapper.loadByLogininId(logininfo.getId());
        //1.保存信息
        msg.setUserId(user.getId());
        searchMasterMsgMapper.save(msg);
        //2.审核
        String str = msg.getName()+msg.getAddress()+msg.getTitle()+msg.getCoatColor();
        //2.1系统自动审核

        //2.1.1 审核不过，记录审核日志
        if(!BaiduAuditUtils.TextCensor(str)){
            SearchMasterMsgAuditLog log = new SearchMasterMsgAuditLog();
            log.setMsgId(msg.getId());
            log.setNote("审核失败，存在敏感信息");
            searchMasterMsgAuditLogMapper.save(log);
            //@TODO 发送审核失败邮件，提醒客人重新修改并提交审核

            msg.setState(-1);

        }else{
            //2.1.2 审核通过，找到最近的店铺，绑定店铺
            //修改审核状态为通过
            msg.setState(1);
            //找到发布寻主消息的人的点
            Point point = DistanceUtil.getPoint(msg.getAddress());
            //查询出所有店铺
            List<Shop> shops = shopMapper.loadAll();
            //找到最近的店铺
            Shop nearestShop = DistanceUtil.getNearestShop(point, shops);
            if(nearestShop!=null){
                //说明找到了，绑定店铺，给老板发消息
                msg.setShopId(nearestShop.getId());
                //发短信
                log.info("亲爱的老板：{}，你的店铺收到新的信息", nearestShop.getName());
            }
            // 找不到，不管：不绑定店铺--> 寻主池
        }
        searchMasterMsgMapper.update(msg);

        //2.人工审核  @TODO
        //2.1 风控系统---系统自动通过约定的规则去审核
        //2.2 部分信息可能需要人工接入审核
    }
}
